﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MapaUsuario.aspx.cs" Inherits="VemTransporte.Views.Mapa.MapaUsuario" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <%--Os aparelhos iPhone respeitam a seguinte tag <meta>:--%>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript" src="../../Scripts/jquery-1.4.1.js"></script>
    <script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

    <script type="text/javascript">
        var geocoder;
        var map;
        var intervalFuncao;

        $(document).ready(function () {
            initialize();

            });
        
        function initialize() {
            geocoder = new google.maps.Geocoder();
            var latlng = new google.maps.LatLng(-8.0013, -34.9246);
            var myOptions = {
                zoom: 17,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(-8.0013, -34.9246),
                map: map,
                title: 'AEROPORTO/AFOGADOS',
                icon: "../../Content/gifs/b_onibus.gif"
            });

            var janela = new google.maps.InfoWindow({
                content: 'Linha 232<br />AEROPORTO/AFOGADOS',
                size: new google.maps.Size(150, 150)
            });
            //                            title: 'Marcador',
            //              icon: "http://labs.google.com/ridefinder/images/mm_20_yellow.png"

            //Adicionando no on click marcador
            google.maps.event.addListener(marker, 'click', function () {
                janela.open(map, marker);
                //map.setZoom(8);
            });
            //google.maps.event.addListener(map, 'click', function () {
            //janela.open(map, janela);
            //});

            //detectBrowser();
            procurarTransportePorUsuario();
        }
        //var IdUsuarioLogado = '<%=Session["IdUsuarioLogado"] %>';
        function procurarTransportePorUsuario() {

            var IdUsuarioLogado = '<%=Session["IdUsuarioLogado"] %>';
            var IdLinhaUsuarioLogado = '<%=Session["IdLinhaUsuarioLogado"] %>';

            $.ajax({
                //Metodo utilizado
                type: "POST",
                //Url webservices
                url: "/ServiceData/ProcurarTransporteUsuario",
                contentType: "application/json",
                //String de dados enviada
                data: '{"IdUsuario":' + IdUsuarioLogado + '}',
                processData: false,
                //Inicio da funcao que requisita a resposta da pagina onde recebeu os dados
                success: function (msg) {
                    alert(msg);
                },
                error: function (msg) {
                    alert("ERRO INESPERADO NO SERVIDOR. ");
                }
            });       

            if (intervalFuncao) {
                clearTimeout(intervalFuncao);
                intervalFuncao = setTimeout("procurarTransportePorUsuario()", 10000);
            }
            else {
                intervalFuncao = setTimeout("procurarTransportePorUsuario()", 10000);
            }/**/
        }

        function AjaxSucceeded(result) {
            
        }
       

       function marcaPonto(latitude, longitude, dica, balaoTexto) {
           var marker = new google.maps.Marker({
               position: new google.maps.LatLng(latitude, longitude),
                map: map,
                title: dica,
                icon: "../../Content/gifs/b_onibus.gif"
            });

        var janela = new google.maps.InfoWindow({
        content: balaoTexto,
        size: new google.maps.Size(150, 150)
        });
        //                            title: 'Marcador',
        //              icon: "http://labs.google.com/ridefinder/images/mm_20_yellow.png"

        //Adicionando no on click marcador
        google.maps.event.addListener(marker, 'click', function () {
        janela.open(map, marker);
        //map.setZoom(8);
        });
        }/**/

        function centerMap(latitude, longitude) {
            map.setCenter(new google.maps.LatLng(latitude, longitude));
        }

        function codeAddress() {
            var address = document.getElementById("address").value;
            if (geocoder) {
                geocoder.geocode({ 'address': address }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                        marcaPonto(results[0].geometry.location.lat(), results[0].geometry.location.lng(), "Você está aqui!", "Seu endereço");
                        centerMap(results[0].geometry.location.lat(), results[0].geometry.location.lng());
                        alert(results[0].formatted_address);
                        alert(results[0].types.join(", "));
                    } else {
                        alert("Localização não encontrada: " + status);
                    }
                });
            }
        }


        function submitQuery() {
            var query = document.getElementById("address").value;
            if (/\s*^\-?\d+(\.\d+)?\s*\,\s*\-?\d+(\.\d+)?\s*$/.test(query)) {
                var latlng = parseLatLng(query);
                if (latlng == null) {
                document.getElementById("query").value = "";
                } else {
                    geocode({ 'latLng': latlng });
                }
                } else {
                geocode({ 'address': query });
            }
        }

        function parseLatLng(value) {
        value.replace('/\s//g');
        var coords = value.split(',');
        var lat = parseFloat(coords[0]);
        var lng = parseFloat(coords[1]);
        if (isNaN(lat) || isNaN(lng)) {
        return null;
        } else {
        return new google.maps.LatLng(lat, lng);
        }
        }

        function geocode(request) {
        geocoder.geocode(request, showResults);
        }


 
        //<script type="text/javascript">
        //      $(document).ready(function() {
        //          $.ajax({
        //              type: "POST",
        //              url: "pagemethod.aspx/sayHello",
        //              contentType: "application/json; charset=utf-8",
        //              data: "{}",
        //              dataType: "json",
        //              success: AjaxSucceeded,
        //              error: AjaxFailed
        //          }); 
        //    });
        //      function AjaxSucceeded(result) {
        //          alert(result.d);
        //      }
        //      function AjaxFailed(result) {
        //          alert(result.status + ' ' + result.statusText);
        //      }  /**/


    </script>
</head>
<body>
    <div id="matches"></div> 

    <input type="text" size="80" name="address" id="address" value="Endereço" />
    <input type="button" value="Buscar!" onclick="codeAddress()" />
    <br />
    <div id="responseInfo"> 
      <div id="responseStatus"> 
        <div> 
          <span style="font-weight: bold">Geocoder response: </span> 
          <span id="statusValue"></span> (<span id="statusDescription"></span>)
        </div> 
      </div> 
      <div id="responseCount"> 
        <span style="font-weight: bold;">Matches returned: </span> 
        <span id="matchCount"></span> 
      </div> 
    </div> 
    <br />
    <input type="text" size="30" name="latitude" id="latitude" value="latitude" />
    <input type="text" size="30" name="longitude" id="longitude" value="longitude" />
    <input type="button" value="Go!" onclick="marcaPonto(document.getElementById('latitude').value, document.getElementById('longitude').value, 'Sua marcação', 'Aqui!'); centerMap(document.getElementById('latitude').value, document.getElementById('longitude').value)") />
    <div id="map_canvas" style="width: 100%; height: 100%">
    </div>


</body>
</html>
